package com.zhang.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mysql.cj.util.StringUtils;
import com.zhang.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.gulimall.common.utils.PageUtils;
import com.zhang.gulimall.common.utils.Query;

import com.zhang.gulimall.product.dao.CategoryDao;
import com.zhang.gulimall.product.entity.CategoryEntity;
import com.zhang.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    private final Map<String,Object> cache = new HashMap<>();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listCategoryWithTree() {
        List<CategoryEntity> list = baseMapper.selectList(null);
        return list.stream()
                .filter(category -> category.getParentCid().equals("0"))
                .peek(category -> category.setChildren(collect(category, list)))
                .collect(Collectors.toList());

    }

    @Override
    public String[] findCategoryPath(String catelogId) {
        List<String> list = new ArrayList<>();
        list.add(catelogId);
        CategoryEntity category = baseMapper.selectById(catelogId);
        while (!category.getParentCid().equals("0")){
            list.add(category.getParentCid());
            category = baseMapper.selectById(category.getParentCid());
        }
        Collections.reverse(list);
        return list.toArray(new String[0]);
    }

    @Cacheable(value = {"category"},key = "'level1category'")
    @Override
    public List<CategoryEntity> listLevel1() {
        System.out.println("查询了一遍");
        return baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().lambda()
                        .eq(CategoryEntity::getCatLevel,1));
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        String catlogJson = redisTemplate.opsForValue().get("catlogJson");
        if (!StringUtils.isEmptyOrWhitespaceOnly(catlogJson)){
            return JSON.parseObject(catlogJson,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }
        Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
        redisTemplate.opsForValue().set("catlogJson", JSON.toJSONString(catalogJsonFromDb));
        return catalogJsonFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        Map<String, List<Catelog2Vo>> catalogJson = (Map<String, List<Catelog2Vo>>)cache.get("catalogJson");
        if (catalogJson!=null){
            return  catalogJson;
        }
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<>());
        List<CategoryEntity> level1 = listLevel(categoryEntities,"0");
        Map<String, List<Catelog2Vo>> collect2 = level1.stream().collect(Collectors.toMap(CategoryEntity::getCatId, l1 -> {
            List<CategoryEntity> level2 = listLevel(categoryEntities, l1.getCatId());
            List<Catelog2Vo> collect = null;
            if (level2 != null) {
                collect = level2.stream().map(l2 -> {
                    List<CategoryEntity> level3 = listLevel(categoryEntities, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> collect1 = null;
                    if (level3 != null) {
                        collect1 = level3.stream().map(l3 -> new Catelog2Vo.Catelog3Vo(l3.getParentCid(), l3.getCatId(), l3.getName())).collect(Collectors.toList());
                    }
                    return new Catelog2Vo(l1.getCatId(), collect1, l2.getCatId(), l2.getName());

                }).collect(Collectors.toList());
            }
            return collect;
        }));
        cache.put("catalogJson",collect2);
        return collect2;
    }

    public List<CategoryEntity> listLevel(List<CategoryEntity> categoryEntities, String id) {
        return categoryEntities.stream().filter(v-> v.getParentCid().equals(id)).collect(Collectors.toList());
    }

    public List<CategoryEntity> collect(CategoryEntity entity, List<CategoryEntity> all) {
        return all.stream()
                .filter(category -> category.getParentCid().equals(entity.getCatId()))
                .peek(category -> category.setChildren(collect(category, all)))
                .collect(Collectors.toList());
    }

}